package org.practice.springaichatmemory.service;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

@Service
public class ChatCleanupService {
    
    private static final Logger logger = Logger.getLogger(ChatCleanupService.class.getName());
    
    private final ChatMemory chatMemory;
    
    // 存储会话的最后访问时间
    private final Map<String, LocalDateTime> sessionLastAccess = new ConcurrentHashMap<>();
    
    // 会话过期时间（分钟），默认为30分钟
    @Value("${chat.session.expiration:30}")
    private int sessionExpirationMinutes;
    
    // 每个会话的最大消息数，默认为10条
    @Value("${chat.session.max-messages:10}")
    private int maxMessagesPerSession;
    
    @Autowired
    public ChatCleanupService(ChatMemory chatMemory) {
        this.chatMemory = chatMemory;
    }
    
    /**
     * 每隔10分钟执行一次清理任务
     */
    @Scheduled(fixedRate = 600000) // 10分钟 = 600,000毫秒
    public void cleanupExpiredSessions() {
        logger.info("开始执行聊天记录清理任务...");
        
        LocalDateTime now = LocalDateTime.now();
        int cleanedCount = 0;
        
        // 检查所有会话的最后访问时间
        for (Map.Entry<String, LocalDateTime> entry : sessionLastAccess.entrySet()) {
            String sessionId = entry.getKey();
            LocalDateTime lastAccess = entry.getValue();
            
            // 如果会话已过期，则清理它
            if (now.isAfter(lastAccess.plusMinutes(sessionExpirationMinutes))) {
                chatMemory.clear(sessionId);
                sessionLastAccess.remove(sessionId);
                cleanedCount++;
                logger.info("已清理过期会话: " + sessionId);
            }
        }
        
        logger.info("聊天记录清理任务完成，共清理了 " + cleanedCount + " 个过期会话");
    }
    
    /**
     * 更新会话的最后访问时间
     * @param sessionId 会话ID
     */
    public void updateSessionAccessTime(String sessionId) {
        sessionLastAccess.put(sessionId, LocalDateTime.now());
    }
    
    /**
     * 获取当前跟踪的会话数量
     * @return 会话数量
     */
    public int getTrackedSessionCount() {
        return sessionLastAccess.size();
    }
    
    /**
     * 获取每个会话的最大消息数限制
     * @return 最大消息数
     */
    public int getMaxMessagesPerSession() {
        return maxMessagesPerSession;
    }
}